<template>
  <Wrapper>
    <el-button type="primary" @click="handleExport">导出</el-button>

    <el-table :data="tableData">
      <el-table-column prop="date" label="Date" />
      <el-table-column label="Address Info">
        <el-table-column prop="state" label="State" />
        <el-table-column prop="city" label="City" />
        <el-table-column prop="address" label="Address" />
      </el-table-column>
      <el-table-column prop="name" label="Name" />
    </el-table>
  </Wrapper>
</template>

<script setup>
import { parseTime } from '@/utils/utils'

const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
  {
    date: '2016-05-08',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
  {
    date: '2016-05-06',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
  {
    date: '2016-05-07',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
  },
]

function handleExport() {
  import('@/plugins/export-excel').then((excel) => {
    const multiHeader = [['日期', '地址信息', '', '', '姓名']]
    const tHeader = ['', 'State', 'City', 'Address', '']
    const filterVal = ['date', 'state', 'city', 'address', 'name']
    const data = formatJson(filterVal, tableData)

    excel.export_json_to_excel({
      multiHeader,
      header: tHeader,
      data,
      merges: ['A1:A2', 'B1:D1', 'E1:E2'],
      filename: '多级表头',
    })
  })
}

function formatJson(filterVal, jsonData) {
  return jsonData.map((v) =>
    filterVal.map((j) => {
      if (j === 'timestamp') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
    }),
  )
}
</script>
